import path from 'path'
import sharp from 'sharp'

export default function imageCompressPlugin() {
  return {
    name: 'vite-plugin-image-compress',
    enforce: 'post',

    async generateBundle(_, bundle) {
      for (const fileName in bundle) {
        const chunk = bundle[fileName]

        if (chunk.type === 'asset' && /\.(png|jpe?g)$/i.test(chunk.fileName)) {
          try {
            // 压缩图片（在这里可以使用第三方库进行压缩）
            console.log('压缩图片：', chunk.fileName);            
            let sourceFileSize = chunk.source.length;
            const outputPath = path.resolve(process.cwd(), 'dist', chunk.fileName);
            const compressedBuffer = await sharp(chunk.source)
              .jpeg({ quality: 80 })
              .toBuffer();
            chunk.source = compressedBuffer;
            console.log('压缩成功：', chunk.fileName);
            // 压缩率：
            console.log('压缩率：', (compressedBuffer.length / sourceFileSize).toFixed(2));                        
          } catch (error) {
            // 压缩失败
          }
        }
      }
    }
  }
}
